package com.ssh.entity;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Cart implements Serializable {

	private static final long serialVersionUID = 4046850333793968585L;

	private Map<Integer, CartItem> itemMap = new HashMap<Integer, CartItem>();
	
	private Double total=0.0;
	
	@SuppressWarnings("unused")
	private Collection<CartItem> cartItems;
	
	public Collection<CartItem> getCartItems(){
		return itemMap.values();
	}
	
	public Map<Integer, CartItem> getItemMap() {
		return itemMap;
	}

	public void setItemMap(Map<Integer, CartItem> itemMap) {
		this.itemMap = itemMap;
	}

	public Double getTotal() {
		return total;
	}

	public void setTotal(Double total) {
		this.total = total;
	}
	
	/**
	 * 加入购物车
	 * @param item
	 */
	public void add(CartItem item){
		int pid = item.getProduct().getPid();
		
		if(itemMap.containsKey(pid)){
			// 原来的购物项
			CartItem oItem = itemMap.get(pid);
			
			oItem.setCount(oItem.getCount() + item.getCount());
		}else{
			itemMap.put(pid, item);
		}
		total += item.getSubtotal();
	}
	
	

	/**
	 * 移除购物项
	 * @param item
	 */
	public void remove(Integer pid){
		CartItem item = itemMap.remove(pid);
		
		total -= item.getSubtotal();
	}
	
	/**
	 * 清空购物车
	 * @param item
	 */
	public void clear(){
		// 1.清空map集合
		itemMap.clear();
		
		total = 0.0;
	}
}
